package com.cxf.windex.base.util;

import com.github.wxpay.sdk.WXPayConfig;
import com.github.wxpay.sdk.WXPayConstants;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;

/**
 * @author chenxf
 * @date 3/26/2018
 * @description
 */
public class MD5Util {
  private static String byteArrayToHexString(byte b[]) {
    StringBuffer resultSb = new StringBuffer();
    for (int i = 0; i < b.length; i++)
      resultSb.append(byteToHexString(b[i]));

    return resultSb.toString();
  }

  private static String byteToHexString(byte b) {
    int n = b;
    if (n < 0) {
      n += 256;
    }
    int d1 = n / 16;
    int d2 = n % 16;
    return hexDigits[d1] + hexDigits[d2];
  }

  public static String MD5Encode(String origin, String charsetname) {
    String resultString = null;
    try {
      resultString = new String(origin);
      MessageDigest md = MessageDigest.getInstance("MD5");
      if (charsetname == null || "".equals(charsetname)) {
        resultString = byteArrayToHexString(md.digest(resultString
            .getBytes()));
      }else {
        resultString = byteArrayToHexString(md.digest(resultString
            .getBytes(charsetname)));
      }
    } catch (Exception exception) {
    }
    return resultString;
  }

  public static String getSign(Map<String, String> data,WXPayConfig config) {
    Set<String> keySet = data.keySet();
    String[] keyArray = keySet.toArray(new String[keySet.size()]);
    Arrays.sort(keyArray);
    StringBuilder sb = new StringBuilder();
    for (String k : keyArray) {
      if (k.equals(WXPayConstants.FIELD_SIGN)) {
        continue;
      }
      if (data.get(k)!=null && data.get(k).trim().length() > 0) {// 参数值为空，则不参与签名
        sb.append(k).append("=").append(data.get(k).trim()).append("&");
      }
    }
    sb.append("key=").append(config.getKey());
    MessageDigest md = null;
    try {
      md = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    byte[] array = new byte[0];
    try {
      array = md.digest(sb.toString().getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    StringBuilder sb2 = new StringBuilder();
    for (byte item : array) {
      sb2.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
    }
    return sb2.toString().toUpperCase();
  }


  private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
      "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
}
